/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * 
 * Copyright 2010 yura, Version 2.0 (the "License");
 *
 * you may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * 
 * Unless required by applicable law or agreed to in writing, software
 *
 * distributed under the License is distributed on an "AS IS" BASIS,
 *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 *
 * limitations under the License.
 */

package org.opu.doc2db.document.datadocument.io;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import org.opu.doc2db.document.datadocument.Document;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

/**
 * This class work with XML description of document
 *
 * @author yura
 */
public class DefaultDocumentWriter implements DocumentWriter{

    protected Document document;
    protected Serializer serializer;

    /**
     * Create writer with seted document
     *
     * @param document document thet will be writed
     */
    public DefaultDocumentWriter(Document document) {
        this.document = document;
        this.serializer = new Persister();
    }

    /**
     * Get the value of document
     *
     * @return the value of document
     */
    public Document getDocument() {
        return document;
    }
    /**
     * Set the value of document
     *
     * @param document new value of document
     */
    public void setDocument(Document document) {
        this.document = document;
    }

    @Override
    public void write(OutputStream out) throws IOException{
        try {
            serializer.write(document, out);
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }

    @Override
    public void write(Writer writer) throws IOException{
        try {
            serializer.write(document, writer);
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }

    @Override
    public void write(File file) throws IOException{
        try {
            serializer.write(document, file);
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }

    /**
     * Present Document class to XML format
     *
     * @return string content all data in XML presentation
     */
    public String docToString() throws IOException {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        try {
            serializer.write(document, bout);
        } catch (Exception ex) {
            throw new IOException(ex);
        }
        return new String(bout.toByteArray());
    }

}
